<template>
  <div class="login">
    <div class="login-form">
      <el-form ref="formRef" style="max-width: 600px" :model="ruleForm" label-width="auto" class="demo-ruleForm">
        <el-form-item label="" prop="username" :rules="[
        { required: true, message: '请输入用户名' },
      ]">
          <el-input v-model.number="ruleForm.username" placeholder="账号" type="text" autocomplete="off" />
        </el-form-item>
        <el-form-item label="" prop="password" :rules="[
        { required: true, message: '请输入密码' },
      ]">
          <el-input v-model.number="ruleForm.password" placeholder="密码" type="password" autocomplete="off" />
        </el-form-item>
        {{dataCode}}
        <el-form-item label="" :rules="[{ required: true, message: '请输入验证码' }]">
          <el-button @click="refreshCode" style="position: absolute;z-index: 99;right: 0;">{{dataCode}}</el-button>
          <el-input type="text" v-model.trim="CodeText" placeholder="请输入验证码">
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button class="submitBtn" type="primary" @click="submitForm(formRef)">登录</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref, toRefs } from "vue";
import type { FormInstance } from "element-plus";
import { ElMessage } from "element-plus";
// import { LoginData, CodeData } from "@/type/login";
import https from "@/common/api";
import JsEncrypt from "jsencrypt";
import { useRouter } from "vue-router";
import { el } from "node_modules/element-plus/es/locale";
const formRef = ref<FormInstance>();
// const LoginCode = reactive(new LoginData());
// 表单
let ruleForm = reactive({
  username: "admin",
  password: "Zxc678678",
});
// 验证码
let dataCode = ref("");
let CodeText = ref("");
// 公钥
let publicKey = ref("");
// 获取 router 才能跳转
const router = useRouter();
// 登录
const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate((valid) => {
    if (valid) {
      if (CodeText.value !== dataCode.value) {
        ElMessage.error("验证码错误");
        return;
      }
      let datas = JSON.parse(JSON.stringify(ruleForm));
      let datasStr = RSAencrypt(JSON.stringify(datas), publicKey.value);
      let LoginForm = reactive({
        data: datasStr,
        code: CodeText.value,
      });

      https
        .login(LoginForm)
        .then(({ data }) => {
          console.log(data);
          localStorage.setItem("tokenB", data.token);
          localStorage.setItem("usernameB", data.username);
          localStorage.setItem("userIdB", data.id);
          // 加密
          UserRsaKey();
          Promise.all([getList(), getBtnList()])
            .then((res) => {
              console.log(res, "res");
              let data0 = res[0].data;
              let data1 = res[1];

              if (!data0.length) {
                ElMessage.warning("未拥有菜单权限，请联系管理员分配权限后重试");
                localStorage.clear();
                sessionStorage.clear();
                return;
              }
              router.push({
                path: "/",
              });
              localStorage.setItem("buttonListB", JSON.stringify(data1));
            })
            .catch((err) => {
              console.log(err);
            });
          ElMessage.success("登录成功");
        })
        .catch((err) => {
          LoginCode();
          ElMessage.error(err);
        });
    } else {
      console.log("error submit!");
      return false;
    }
  });
};

function RSAencrypt(pas: any, pubKey: any) {
  JsEncrypt.prototype.setPublicKey(pubKey);
  return JsEncrypt.prototype.encrypt(pas);
}
// 获取验证码
function LoginCode() {
  https.getLoginCode({}).then((res) => {
    dataCode.value = res.data;
    // 获取公钥
    https.getLoginPubKey({ code: dataCode.value }).then((res) => {
      publicKey.value = res.data;
    });
  });
}
// 点击切换验证码
function refreshCode() {
  LoginCode();
}
// 加密
function UserRsaKey() {
  https.getUserRsaKey({}).then((res) => {
    localStorage.setItem("pubKeyB", res.data);
  });
}
// 获取列表
function getList() {
  const promise = new Promise((resolve) => {
    https.getMenu({}).then((data) => {
      console.log(data);
      resolve(data);
    });
  });
  return promise;
}
// 获取按钮显示列表
function getBtnList() {
  const promise = new Promise((resolve) => {
    https.getBtnList({}).then((res) => {
      console.log(res);
    });
  });
}
onMounted(() => {
  LoginCode();
  getList();
  getBtnList();
});
</script>
<style lang="scss" scoped>
.login {
  background: #09c;
  height: 100vh;
  position: relative;
  .login-form {
    width: 300px;
    background: #ccc;
    padding: 20px;
    border-radius: 20px;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
  }
  .submitBtn {
    width: 100% !important;
  }
}
</style>

